package nz.ac.massey.cs.se400_2013.ass3.gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.ServiceLoader;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import nz.ac.massey.cs.se400_2013.ass3.plugin.ChangeListener;
import nz.ac.massey.cs.se400_2013.ass3.EditorPlugin;

public class DomainEditor extends JFrame {

	private Toolbar tool = new Toolbar();
	private SideTree sideTree = new SideTree(this.tool);
	private JPanel currentEditor = new JPanel(); //= (new DefaultEditor().edit(new Student())).getEditor(); //just to fill space since we dont know which plugin to use
	private EditorPlugin editor = new DefaultEditor();
	private SaveHandler handler = null;
	
	public DomainEditor() {
		super();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setJMenuBar(tool);
		
		this.sideTree.addTreeSelectionHandler(new SelectionHandler());
		setLayout(new GridLayout(1, 2));
		this.currentEditor.setLayout(new FlowLayout());
		tool.addPaperHandler(new AddPaperHandler(sideTree));
		tool.addCourseHandler(new AddCourseHandler(sideTree));
		tool.addStudentHandler(new AddStudentHandler(sideTree));
		tool.addDeleteHandler(new DeleteHandler(sideTree));
		tool.addSaveHandler(new SaveHandler(sideTree, editor));
		
		add(sideTree);
		add(currentEditor);
		setSize(1000, 500);
		setVisible(true);
	}

	public static void main(String[] args) {
		new DomainEditor();
	}


	private class SelectionHandler implements TreeSelectionListener{
		
		public <T> T loadService(Class<T> api, Class type){
			T result = null;
			System.out.println("api " + api);
			ServiceLoader<T> impl = ServiceLoader.load(api);

			for (T loadedImpl : impl){
				if (((EditorPlugin) loadedImpl).canEditInstanceOf(type) == true){
					result = loadedImpl;
					break;
				}
			}
			return result;
		}

		public void valueChanged(TreeSelectionEvent e) {
			tool.setSaveEnabled(false);
			Object currentObject = sideTree.getCurrentObject();

			editor = loadService(EditorPlugin.class, currentObject.getClass());
			System.out.println(editor);
			if (editor != null) {
				JPanel neweditor = editor.getEditor();
				editor.edit(currentObject);
				editor.addChangeListener(new ChangeHandler());
				if (handler != null){
					tool.removeSaveHandler(handler);
				}
				handler = new SaveHandler(sideTree, editor);
				tool.addSaveHandler(handler);
				currentEditor.removeAll();
				currentEditor.add(neweditor);
			}
			else {
				editor = new DefaultEditor();
				JPanel neweditor = editor.getEditor();
				editor.edit(currentObject);
				currentEditor.removeAll();
				currentEditor.add(neweditor);
			}
			currentEditor.repaint();
			currentEditor.revalidate();
		}
		
		private class ChangeHandler implements ChangeListener{
			@Override
			public void change() {
				tool.setSaveEnabled(true);
			}
		}
	}
}
